import QtQuick 1.1
//import com.nokia.symbian 1.1
import com.nokia.meego 1.0
import com.nokia.extras 1.1
import "UIConstants.js" as UI
import "platform.js" as PLATFORM
import NumismatMobile 1.0

Page {
    tools: commonTools

    Rectangle {
        anchors.fill: parent
        color: visual.colorBackgrond
    }

    Component {
        id: listDelegate

        Item {
            id: delegateItem
            width: listView.width
            height: UI.LIST_ITEM_HEIGHT_DEFAULT

            Row {
                spacing: 5
                anchors.verticalCenter: parent.verticalCenter
                Image {
                    id: coinImage
                    height: imgheight > UI.LIST_ITEM_HEIGHT_DEFAULT ? UI.LIST_ITEM_HEIGHT_DEFAULT : imgheight
                    width: imgwidth
                    source: "data:image/png;base64," + image
                    smooth: true
                    fillMode: Image.PreserveAspectFit
                }
                Column {
                    width: listView.width - coinImage.width - countBubble.width - 15
                    spacing: 5
                    Text {
                        text: title
                        width: parent.width
                        elide: Text.ElideRight
                        font.pixelSize: UI.FONT_DEFAULT
                        font.bold: true
                        color: UI.COLOR_FOREGROUND
                    }
                    Text {
                        function makeDescription() {
                            var desc = value + " " + unit;
                            if (year)
                                desc += ", " + year;
                            if (coinModel.view == CoinModel.CommemorativeWorld)
                                if (country)
                                    desc += ", " + country;
                            if (mintmark)
                                desc += ", " + mintmark;
                            if (mintage)
                                desc += ", " + qsTr("Mintage: ") + mintage;
                            if (series)
                                desc += ", " + series;
                            return desc
                        }

                        text: makeDescription()
                        width: parent.width
                        elide: Text.ElideRight
                        font.pixelSize: UI.FONT_SMALL
                        color: UI.COLOR_SECONDARY_FOREGROUND
                    }
                }
                CountBubble {
                    id: countBubble
                    visible: count > 0
                    value: count
                    largeSized: true
                }
            }

            MouseArea {
                anchors.fill: parent
                onClicked: {
                    detailsPage.coin = coinModel.get(index);
                    pageStack.push(detailsPage);
                }
                onPressed: {
                    listView.currentIndex = index;
                }
                onReleased: {
                    listView.currentIndex = -1;
                }
                onCanceled: {
                    listView.currentIndex = -1;
                }
                onPressAndHold: {
                    listMenu.coin = coinModel.get(index);
                    listMenu.index = index;
                    listMenu.count = count;
                    listMenu.open()
                }
            }
        }
    }

    Component {
        id: sectionHeading

        Rectangle {
            width: listView.width
            height: headerText.height
            color: "lightsteelblue"

            Item {
                anchors.fill: parent
                anchors.rightMargin: UI.DEFAULT_MARGIN
                anchors.leftMargin: UI.DEFAULT_MARGIN

                Text {
                    id: headerText
                    text: section
                    width: parent.width
                    horizontalAlignment: Text.AlignRight
                    font.pixelSize: UI.FONT_XSMALL
                    font.bold: true
                    color: UI.COLOR_SECONDARY_FOREGROUND
                }
            }
        }
    }

    property string __colorString: "color19-"
    property bool inverted: theme.inverted
    property string __invertedString: inverted? "-inverted" : ""
    property url highlightBackground: "image://theme/" + __colorString + "meegotouch-list-fullwidth" + __invertedString + "-background-selected"
    ListView {
        id: listView
        width: parent.width
        anchors.top: viewHeader.bottom
        anchors.bottom: parent.bottom
        focus: true
        model: coinModel
        highlightFollowsCurrentItem: true
        currentIndex: -1
        delegate: listDelegate
        section.property: "year"
        section.criteria: ViewSection.FullString
        section.delegate: sectionHeading
        highlightMoveSpeed: -1
        highlight: BorderImage {
            source: highlightBackground
            horizontalTileMode: BorderImage.Stretch
            verticalTileMode: BorderImage.Stretch
            width: listView.width
        }
    }

    ScrollDecorator {
        flickableItem: listView
    }

    ListModel {
        id: seriesModel
        function fill() {
            seriesModel.clear();
            for (var i in coinModel.seriesModel) {
                var series = coinModel.seriesModel[i];
                seriesModel.append({'name': series});
            }
            seriesSelectionDialog.selectedIndex = 0;
            seriesSelectionDialog.series = coinModel.seriesModel[0];
        }
    }

    property bool started: false
    onStatusChanged: {
        if (status == PageStatus.Active) {
            if (!started) {
                started = true;
                // First run
                if (coinModel.lastCollection() === '') {
                    selectSource.open();
                }
                else {
                    openDb(coinModel.lastCollection());
                }
            }

            statusBar.text = coinModel.fileTitle()
        }
    }

    function openDb(newFile) {
        openAction.file = newFile;
        openAction.start();
    }

    BusyAction {
        id: openAction
        property string file

        onWork: {
            if (coinModel.open(file)) {
                seriesModel.fill();
                statusBar.text = coinModel.fileTitle()
            }
            else {
                fileDialog.folder = 'file:///'+coinModel.folder();
                pageStack.push(fileDialog);
            }
        }
    }

    SelectionDialog {
        id: seriesSelectionDialog
        titleText: coinModel.view == CoinModel.CommemorativeWorld ? qsTr("Select country") : qsTr("Select series")
        selectedIndex: 0
        model: seriesModel
        property string series: seriesModel.count ? coinModel.seriesModel[selectedIndex] : ''
        onAccepted: {
            series = coinModel.seriesModel[selectedIndex];
            seriesAction.start();
            listView.visible = false;
        }
    }

    BusyAction {
        id: seriesAction

        onWork: {
            coinModel.series = seriesSelectionDialog.selectedIndex;
            listView.visible = true;
        }
    }

    ViewHeader {
        id: viewHeader
        onClicked: seriesSelectionDialog.open()
        content: Item {
            anchors.fill: parent
            Text {
                text: seriesSelectionDialog.series
                anchors.verticalCenter: parent.verticalCenter
                width: parent.width - icon.width
                elide: Text.ElideRight
                font.pixelSize: visual.fontXlarge
                color: visual.colorInvertedForeground
            }
            Image {
                id: icon
                anchors.verticalCenter: parent.verticalCenter
                anchors.right: parent.right
                source: PLATFORM.TYPE == "harmattan" ?
                            "image://theme/icon-m-textinput-combobox-arrow" :
                            privateStyle.imagePath("qtg_graf_choice_list_indicator", false)
            }
        }
    }

    Menu {
        id: listMenu
        property variant coin
        property int index
        property int count

        MenuLayout {
            MenuItem {
                text: qsTr("Add")
                onClicked: {
                    var posY = listView.contentY;
                    coinModel.clone(listMenu.index);
                    listView.contentY = posY;
                }
            }
            MenuItem {
                text: qsTr("Delete")
                enabled: listMenu.count > 0

                onClicked: {
                    deleteConfirmation.coin = listMenu.coin;
                    deleteConfirmation.index = listMenu.index;
                    deleteConfirmation.open();
                }
            }
        }
    }

    Dialog {
        id: deleteConfirmation
        property variant coin
        property int index

        content: Column {
            width: parent.width
            spacing: 8

            Text {
                width: parent.width
                font.pixelSize: UI.FONT_LARGE
                font.bold: true
                horizontalAlignment: Text.AlignHCenter
                color: UI.COLOR_INVERTED_FOREGROUND
                text: qsTr("Delete the coin from collection?")
            }
            Text {
                width: parent.width
                font.pixelSize: UI.FONT_DEFAULT
                horizontalAlignment: Text.AlignHCenter
                color: UI.COLOR_INVERTED_FOREGROUND
                text: deleteConfirmation.coin ? deleteConfirmation.coin.title : ''
                wrapMode: Text.Wrap
            }
        }

        buttons: ButtonColumn {
            anchors.horizontalCenter: parent.horizontalCenter
            spacing: 8

            Button {text: qsTr("Yes"); onClicked: deleteConfirmation.accept()}
            Button {text: qsTr("No"); onClicked: deleteConfirmation.reject()}
        }

        onAccepted: {
            var posY = listView.contentY;
            coinModel.remove(deleteConfirmation.index)
            listView.contentY = posY;
        }
    }

    Dialog {
        id: selectSource

        title: Text {
            width: parent.width
            font.pixelSize: UI.FONT_LARGE
            font.bold: true
            horizontalAlignment: Text.AlignHCenter
            color: UI.COLOR_INVERTED_FOREGROUND
            text: qsTr("Select collection")
        }

        content: Text {
            width: parent.width
            font.pixelSize: UI.FONT_DEFAULT
            horizontalAlignment: Text.AlignHCenter
            color: UI.COLOR_INVERTED_FOREGROUND
            text: qsTr("Where from get collection for working?")
            wrapMode: Text.Wrap
        }

        buttons: ButtonColumn {
            anchors.horizontalCenter: parent.horizontalCenter
            spacing: 8

            Button {text: qsTr("Download from web"); onClicked: selectSource.accept()}
            Button {text: qsTr("Open existen"); onClicked: selectSource.reject()}
        }

        onAccepted: pageStack.push(downloadPage);
        onRejected: openDb('');
    }
}
